package com.id.coinscleaner.utils

import android.content.Context
import android.telephony.TelephonyManager
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.id.coinscleaner.App.Companion.appContext
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.callbackFlow

/**
 * Created by YiGo on 2022/6/27.
 */


object InstallChannel {
    fun referrer() = callbackFlow<Pair<String, Boolean>> {
        val installReferrerClient = InstallReferrerClient.newBuilder(appContext).build()
        installReferrerClient.startConnection(object : InstallReferrerStateListener {
            override fun onInstallReferrerSetupFinished(responseCode: Int) {
//                Log.w("gyk", "InstallChannel.onInstallReferrerSetupFinished -> $responseCode")
                when (responseCode) {
                    InstallReferrerClient.InstallReferrerResponse.OK -> {

                        val referrer = installReferrerClient.installReferrer.installReferrer
//                        val referrer = "utm_source=am&utm_medium=cpi&utm_content={cid}"
//                        Log.w("gyk", "InstallChannel.onInstallReferrerSetupFinished -> $referrer")
                        val isCampaign = referrer?.isCampaign() ?: false
                        trySendBlocking(Pair(referrer, isCampaign))//发送流
                        close()
                    }
                    else -> close(Exception(getResponseCodeMsg(responseCode)))
                }
//                Log.w("gyk", "InstallChannel.onInstallReferrerSetupFinished -> ${getResponseCodeMsg(responseCode)}")
            }

            override fun onInstallReferrerServiceDisconnected() {
                close(Exception())
            }
        })
        awaitClose()//保持时刻运行
    }


    private fun String.isCampaign(): Boolean {
        val utmArray = split("&")
        var utmSource: String? = null

        for (item in utmArray) {
            if (!item.startsWith("utm_source=")) {
                continue
            }
            utmSource = item.replace("utm_source=", "")
            break
        }

        if (utmSource.isNullOrEmpty()) return false

        if (!hasSimCard()) return false

        return utmSource.contains("am",true)
    }

    private fun hasSimCard(): Boolean {
        val telMgr = appContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val simState = telMgr.simState
        var result = true
        if (simState == TelephonyManager.SIM_STATE_ABSENT) {
            result = false // 没有SIM卡
        } else if (simState == TelephonyManager.SIM_STATE_UNKNOWN) {
            result = false
        }
        return result
    }

    private fun getResponseCodeMsg(responseCode: Int): String {
        return when (responseCode) {
            InstallReferrerClient.InstallReferrerResponse.OK -> "OK"
            InstallReferrerClient.InstallReferrerResponse.SERVICE_DISCONNECTED -> "SERVICE_DISCONNECTED"
            InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> "SERVICE_UNAVAILABLE"
            InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> "FEATURE_NOT_SUPPORTED"
            InstallReferrerClient.InstallReferrerResponse.DEVELOPER_ERROR -> "DEVELOPER_ERROR"
            InstallReferrerClient.InstallReferrerResponse.PERMISSION_ERROR -> "PERMISSION_ERROR"
            else -> "OTHER ERROR"
        }
    }
}